﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace xoafoldertrong

{
    public partial class Form1 : Form
    {
        public DirectoryInfo dti;
        public Form1()
        {
            InitializeComponent();
        }

        private void btnChoose_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog op = new FolderBrowserDialog();
            op.Description = "Chọn thư mục cần xóa Folder";
            if (op.ShowDialog() == DialogResult.OK)
                textBox1.Text = op.SelectedPath.ToString();
        }

        private void btnStartDelete_Click(object sender, EventArgs e)
        {
            label2.Text = "Đang xóa...";
            Application.DoEvents();
            if (new DirectoryInfo(textBox1.Text).Exists)
            {
                duyetthumucdequy(textBox1.Text);
                if (int.Parse(new DirectoryInfo(textBox1.Text).GetDirectories().Length.ToString()) == 0 && int.Parse(new DirectoryInfo(textBox1.Text).GetFiles().Length.ToString()) == 0)
                    Directory.Delete(textBox1.Text);
                label2.Text = "";
                MessageBox.Show("Đã xóa xong");
            }
            else
                MessageBox.Show("Thư mục không tồn tại.Vui lòng chọn lại!","Thông Báo",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
        }
        private void duyetthumucdequy(string folder)
        {
            if (int.Parse(new DirectoryInfo(folder).GetDirectories().Length.ToString()) > 0)
            {
                foreach (DirectoryInfo subfolder in new DirectoryInfo(folder).GetDirectories())
                {
                    try
                    {
                        //Bỏ qua các thư mục hệ thống
                        if (subfolder.Attributes.ToString().Contains("System")) continue;
                        duyetthumucdequy(subfolder.FullName);
                        if (int.Parse(subfolder.GetDirectories().Length.ToString()) == 0 && int.Parse(subfolder.GetFiles().Length.ToString()) == 0)
                            Directory.Delete(subfolder.FullName);
                    }
                    catch { }
                }
            }
        }
    }
}
